package com.njxxted.activiti.common.listener.process;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述：任务监听器模板(采用了模版模式)，所有任务监听器的实现都必须继承此类
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/8/9 9:29 星期五
 */
public abstract class BaseTemplateTaskListener implements TaskListener {

    private static final long serialVersionUID = 1904064237678825260L;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void notify(DelegateTask delegateTask) {
        TaskEntity taskEntity = (TaskEntity) delegateTask;
        logger.debug("触发了任务监听：{}", taskEntity);

        String activityId = taskEntity.getExecution().getActivityId();
        String processDefinitionId = taskEntity.getProcessDefinitionId();

        //执行子类业务逻辑
        execute(delegateTask, processDefinitionId, activityId);
        //获取脚本类型
        int scriptType = getScriptType();
        //执行事件脚本
        exeEventScript(delegateTask, scriptType, processDefinitionId, activityId);
    }

    /**
     * 实现子类的逻辑事务
     *
     * @param delegateTask        委托执行对象
     * @param processDefinitionId 流程定义id
     * @param activityId          节点id
     */
    protected abstract void execute(DelegateTask delegateTask, String processDefinitionId, String activityId);

    /**
     * 获取脚本类型。
     *
     * @return
     */
    protected abstract Integer getScriptType();

    /**
     * 执行事件脚本
     *
     * @param delegateTask
     * @param scriptType
     * @param actDefId
     * @param nodeId
     */
    private void exeEventScript(DelegateTask delegateTask, int scriptType, String actDefId, String nodeId) {
        logger.debug("enter the baseTaskListener exeEventScript method...");
//        BpmNodeScriptService bpmNodeScriptService=(BpmNodeScriptService)AppUtil.getBean("bpmNodeScriptService");
//        BpmNodeScript model=bpmNodeScriptService.getScriptByType(nodeId, actDefId,scriptType);
//        if(model==null) return;
//
//        String script=model.getScript();
//        if(StringUtil.isEmpty(script)) return;
//
//        GroovyScriptEngine scriptEngine=(GroovyScriptEngine)AppUtil.getBean("scriptEngine");
//        Map<String, Object> vars=delegateTask.getVariables();
//
//        vars.put("task", delegateTask);
//        scriptEngine.execute(script, vars);

    }

}
